const Person = require('../models/person')
const setOutputModel = require('../tools/setOutput')
const setOutput = setOutputModel.setOutput

class PersonController {
  prefix = ''
  getPath(name){
    return name ? `/${this.prefix}/${name}` : `/${this.prefix}`
  }

  async add(ctx, next){ 
    ctx.verifyParams({
      name: { type: "string", required: true }
    })
    let obj = {...ctx.request.body} 
    
    const [addErr, target] = await to( new Person(obj).save() )
    if(addErr) return ctx.throw(500, addErr)  
    ctx.response.body = setOutput(target.toJSON())
  }

  async find(ctx, next) {  
    const {page = 1, pageSize = 20} = ctx.request.query
    // const nameReg = new RegExp(name, 'i')
    const params = {}
    Object.keys(ctx.request.query).forEach((key) => {
      if (ctx.request.query[key]) {
        params[key] = ctx.request.query[key]
      }
    })
    delete params.page
    delete params.pageSize
    const total = await Person.count({
     ...params
    })

    const list = await Person.find({
      ...params
    }) 
    .skip((parseInt(page) - 1) * parseInt(pageSize))
    .limit(parseInt(pageSize) || 5).lean() 
    // console.log('list', list)
    const data = {
      list: list,
      total: total
    }
    ctx.response.body = setOutput(data, 'fetch')
  }

  async findOne(ctx, next) {
    const [err, data] = await to(Person.findById(ctx.params.id).lean()) 
    if(err || !data) return ctx.throw(500, err) 
    ctx.response.body = setOutput(data, 'get')
  }

  async update(ctx, next){
    ctx.verifyParams({
      id: { type: "string", required: true },
      name: { type: "string", required: true }
    })
    const obj = {...ctx.request.body}

     
    const [err, data] = await to( Person.findByIdAndUpdate(obj.id, obj, { new: true }) )
     
    if(err || !data) return ctx.throw(500, err)
     
    ctx.response.body = setOutput(data, 'update')
  }

  async delete(ctx, next) {
    await Person.deleteOne({ _id: ctx.params.id }) 
    ctx.response.body = {
      data: null,
      code: 0,
      msg: '成功'
    }
  }
}

module.exports = new PersonController()